﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Http;
using distpm.model;
using Microsoft.Owin.Hosting.Starter;
using Nancy;
using Newtonsoft.Json;
using System.IO;
namespace distpm.module
{
    public class HomeModule:NancyModule
    {
        private readonly string dir = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "Img"+Path.DirectorySeparatorChar+DateTime.Now.Month+Path.DirectorySeparatorChar+DateTime.Now.Day;
        public HomeModule()
        {
            Get["/downimg",true] = async (x,token) =>
            {



                var url = Request.Query["url"].ToString();


                if (string.IsNullOrEmpty(url))
                {
                    return JsonConvert.SerializeObject(
                        new JsonModel { Msg = "Url格式错误", Data = null, ResponseResult = ResponseResult.BadUrl });
                }

                if (!url.ToLower().StartsWith("http"))
                {
                    return JsonConvert.SerializeObject(
                          new JsonModel { Msg = "Url格式错误！不是HTTP开头", Data = null, ResponseResult = ResponseResult.BadUrl });
                }
                HttpClient hc = new HttpClient();
                Image img = null;
                try
                {
                    string fileformat = string.Empty;
                    var stream = await hc.GetStreamAsync(url);
                    img = Image.FromStream(stream);
                    var imgformat = GetImageFormat(img, out fileformat);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    var filename = Guid.NewGuid().ToString("N") + fileformat;
                    img.Save(dir + Path.DirectorySeparatorChar + filename);
                    return JsonConvert.SerializeObject(
                        new JsonModel
                        {
                            Msg = "正常",
                            Data =
                                "Img" + Path.DirectorySeparatorChar + DateTime.Now.Month + Path.DirectorySeparatorChar +
                                DateTime.Now.Day + Path.DirectorySeparatorChar + filename,
                            ResponseResult = ResponseResult.Ok
                        });
                }
                catch (Exception e)
                {
                    return Response.AsJson(new JsonModel
                    {
                        Msg = e.ToString(),
                        Data = null,
                        ResponseResult = ResponseResult.Error
                    });
                }
                finally
                {
                    img?.Dispose();
                    hc.Dispose();
                }


                Console.WriteLine(url);
                return JsonConvert.SerializeObject(
                    new JsonModel { Msg = "正常", Data = url, ResponseResult = ResponseResult.Ok });
            };
        }
        /// <summary>
        /// 获取Image图片格式
        /// </summary>
        /// <param name="_img"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        private System.Drawing.Imaging.ImageFormat GetImageFormat(Image _img, out string format)
        {
            if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
            {
                format = ".jpg";
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
            {
                format = ".gif";
                return System.Drawing.Imaging.ImageFormat.Gif;
            }
            if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
            {
                format = ".png";
                return System.Drawing.Imaging.ImageFormat.Png;
            }
            if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
            {
                format = ".bmp";
                return System.Drawing.Imaging.ImageFormat.Bmp;
            }
            format = string.Empty;
            return null;
        }

    }

}